#!/usr/bin/env sh

# ***************************************************************************
# Copyright  (c) 2025 James M. Zhou
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ***************************************************************************

ROOT="$(pwd)"
VERSION="{%VERSION%}"
cd "$(dirname "$0")" || exit
cd "../"
# Navigate to the root directory
cd "$ROOT" || exit

# Java options initialization
JAVA_OPTS=""

# Arguments initialization
args=""

# Loop through each argument
for arg; do
    # Extract the first two characters of the argument
    # str=${arg:0:2}
    str=$(echo "$arg" | awk  '{ string=substr($0, 0, 2); print string; }' )

    # Check if it starts with '-D' or '-X'
    if [ "$str" = "-D" ] || [ "$str" = "-X" ]; then
        JAVA_OPTS="$JAVA_OPTS $arg"
    else
        args="$args $arg"
    fi
done

JAR_FILE=""

# Check if additional JAR files exist and add them to the classpath
# shellcheck disable=SC2043
for jar_file in "$ROOT"/lib/tinystruct-"$VERSION".jar; do
    [ -f "$jar_file" ] && JAR_FILE="$JAR_FILE$jar_file:"
done

# OS specific support.  $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
  CYGWIN*) cygwin=true ;;
  MINGW*) mingw=true;;
  Darwin*) darwin=true
    # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
    # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
    if [ -z "$JAVA_HOME" ]; then
      if [ -x "/usr/libexec/java_home" ]; then
        export JAVA_HOME="`/usr/libexec/java_home`"
      else
        export JAVA_HOME="/Library/Java/Home"
      fi
    fi
    ;;
esac

if [ -z "$JAVA_HOME" ] ; then
  if [ -r /etc/gentoo-release ] ; then
    JAVA_HOME=`java-config --jre-home`
  fi
fi

if [ -z "$M2_HOME" ] ; then
  ## resolve links - $0 may be a link to maven's home
  PRG="$0"

  # need this for relative symlinks
  while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
      PRG="$link"
    else
      PRG="`dirname "$PRG"`/$link"
    fi
  done

  saveddir=`pwd`

  M2_HOME=`dirname "$PRG"`/..

  # make it fully qualified
  M2_HOME=`cd "$M2_HOME" && pwd`

  cd "$saveddir"
  # echo Using m2 at $M2_HOME
fi

# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
  [ -n "$M2_HOME" ] &&
    M2_HOME=`cygpath --unix "$M2_HOME"`
  [ -n "$JAVA_HOME" ] &&
    JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
  [ -n "$CLASSPATH" ] &&
    CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi

# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
  [ -n "$M2_HOME" ] &&
    M2_HOME="`(cd "$M2_HOME"; pwd)`"
  [ -n "$JAVA_HOME" ] &&
    JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
  # TODO classpath?
fi

if [ -z "$JAVA_HOME" ]; then
  javaExecutable="`which javac`"
  if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
    # readlink(1) is not available as standard on Solaris 10.
    readLink=`which readlink`
    if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
      if $darwin ; then
        javaHome="`dirname \"$javaExecutable\"`"
        javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
      else
        javaExecutable="`readlink -f \"$javaExecutable\"`"
      fi
      javaHome="`dirname \"$javaExecutable\"`"
      javaHome=`expr "$javaHome" : '\(.*\)/bin'`
      JAVA_HOME="$javaHome"
      export JAVA_HOME
    fi
  fi
fi

if [ -z "$JAVACMD" ] ; then
  if [ -n "$JAVA_HOME"  ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
      # IBM's JDK on AIX uses strange locations for the executables
      JAVACMD="$JAVA_HOME/jre/sh/java"
    else
      JAVACMD="$JAVA_HOME/bin/java"
    fi
  else
    JAVACMD="`which java`"
  fi
fi

if [ ! -x "$JAVACMD" ] ; then
  echo "Error: JAVA_HOME is not defined correctly." >&2
  echo "  We cannot execute $JAVACMD" >&2
  exit 1
fi

if [ -z "$JAVA_HOME" ] ; then
  echo "Warning: JAVA_HOME environment variable is not set."
fi

# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
  [ -n "$M2_HOME" ] &&
    M2_HOME=`cygpath --path --windows "$M2_HOME"`
  [ -n "$JAVA_HOME" ] &&
    JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
  [ -n "$CLASSPATH" ] &&
    CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
  [ -n "$MAVEN_PROJECTBASEDIR" ] &&
    MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi

# Check if M2_HOME is not set or is equal to the current project path
if [ -z "$M2_HOME" ] || [ "$M2_HOME" = "$(pwd)" ]; then
    # Set M2_HOME to the .m2 folder under the user's home directory
    M2_HOME="$HOME/.m2"
fi

# Add all JAR files under the lib folder to the classpath
for jar_file in "$ROOT"/lib/*.jar; do
    CLASSPATH="$CLASSPATH:$jar_file"
done

# Check if the JAR file exists in .m2
DEFAULT_JAR_FILE="$M2_HOME/repository/org/tinystruct/tinystruct/$VERSION/tinystruct-$VERSION.jar"
[ -f "$DEFAULT_JAR_FILE" ] && JAR_FILE="$DEFAULT_JAR_FILE"

# Check if the JAR file exists in .m2
DEFAULT_JAR_FILE_WITH_DEPENDENCIES="$M2_HOME/repository/org/tinystruct/tinystruct/$VERSION/tinystruct-$VERSION-jar-with-dependencies.jar"
[ -f "$DEFAULT_JAR_FILE_WITH_DEPENDENCIES" ] && JAR_FILE="$DEFAULT_JAR_FILE_WITH_DEPENDENCIES"

# Check if the Maven Wrapper is already available
if [ ! -f "mvnw" ]; then
    echo "Maven Wrapper not found. Extracting from JAR..."

    # Run Java code to extract the ZIP file from the JAR
    $JAVACMD -cp "$JAR_FILE" org.tinystruct.system.Dispatcher maven-wrapper --jar-file-path "$JAR_FILE" --destination-dir "$ROOT"

    if [ -f "$ROOT/maven-wrapper.zip" ]; then
        # Now unzip the Maven Wrapper files
        unzip -q "$ROOT/maven-wrapper.zip" -d "$ROOT"
        # Delete the ZIP file after extraction
        rm -f "$ROOT/maven-wrapper.zip"
        chmod +x ./mvnw
        echo "Maven wrapper setup completed."
    else
        echo "Error: Maven wrapper ZIP file not found in JAR."
        exit 1
    fi
fi


# Java execution
$JAVACMD \
$JAVA_OPTS \
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/ \
-cp "$ROOT/target/classes:$CLASSPATH:$ROOT/WEB-INF/lib/*:$ROOT/WEB-INF/classes:$JAR_FILE" org.tinystruct.system.Dispatcher "$@"